//
// Created by 顾蛟 on 2020/7/4.
//

#include "Triangle.h"
#include "FileUtil.h"
#include "GLUtils.h"

using namespace std;

GLuint program = 0;
GLuint vertexShader;
GLuint fragShader;

void Triangle::init() {
    //rgb数值除以255得到浮点值
    //设置清除背景时的颜色，即有什么颜色作为清除后的背景，这是预设值，调用glClear(GL_COLOR_BUFFER_BIT)时，会使用该颜色值作为背景颜色。
    glClearColor((GLfloat)128/255, (GLfloat)42/255, (GLfloat)42/255, 1.0f);
//    glClearColor(1.0f, 1.0f, 0.5f, 1.0f);

    char vShaderStr[] =
            "#version 300 es                          \n"
            "layout(location = 0) in vec4 vPosition;  \n"
            "void main()                              \n"
            "{                                        \n"
            "   gl_Position = vPosition;              \n"
            "}                                        \n";

    char fShaderStr[] =
            "#version 300 es                              \n"
            "precision mediump float;                     \n"
            "out vec4 fragColor;                          \n"
            "void main()                                  \n"
            "{                                            \n"
            "   fragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );  \n"
            "}                                            \n";
//    string vertexShaderSrc = readFileIntoString("TriangleVertex.glsl");
//    string fragShaderSrc = readFileIntoString("TriangleFragment.glsl");
//    LOGCATD("vertexShader: %s", vertexShaderSrc.c_str());
//    LOGCATD("fragShaderSrc: %s", fragShaderSrc.c_str());
//    program = GLUtils::CreateProgram(vertexShaderSrc.c_str(), fragShaderSrc.c_str(), vertexShader, fragShader);

    program = GLUtils::CreateProgram(vShaderStr, fShaderStr, vertexShader, fragShader);
}

void Triangle::draw() {
    //清除界面
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
    GLfloat vertices[] = {
            0.0f,  0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            0.5f, -0.5f, 0.0f,
    };
    if (program == 0) {
        return;
    }
    glUseProgram(program);
    //第四个参数，当数组中的值被访问并被转换至浮点值时，如果normalized被设置为GL_TRUE，意味着整数型的值会被映射至区间[-1,1](有符号整数)，
    //或者区间[0,1]（无符号整数），反之，这些值会被直接转换为浮点值而不进行归一化处理。
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
}

void Triangle::destroy() {
    if(program) {
        glDeleteProgram(program);
        program = GL_NONE;
    }
}